import React from 'react';
import {App, Button, Card, Form, Input, Radio} from "antd";
import {Link, useLocation, useNavigate} from "react-router-dom";
import {GatewayRoute, GatewayRouteFactory} from "type/entity/GatewayRoute";
import TextArea from "antd/es/input/TextArea";
import {filedArrayToStringObject, stringObjectToFiledArray} from "util/compare";
import {InputMultiple} from "common/form";
import RequestHandler from "http/RequestHandler";

const RouterFactoryUpdate = () => {
    const {router, factory} = useLocation().state as { router: GatewayRoute, factory: GatewayRouteFactory };
    const navigate = useNavigate();
    const { message } = App.useApp();
    const onFinish = async (value: GatewayRouteFactory) => {
        value.args = filedArrayToStringObject(value.args as any);
        value.metadata = filedArrayToStringObject(value.metadata as any);
        const res = await RequestHandler.post<number>("/manager/admin/route/factory", value);
        if (res.success && res.data > 0) {
            message.success("提交修改成功");
            setTimeout(() => navigate("../", {state: router}), 500);
        }else {
            message.info("修改失败");
        }
    };
    const args = stringObjectToFiledArray(factory.args);
    const metadata = stringObjectToFiledArray(factory.metadata);

    return (
        <Card title={"路由工厂更新"} extra={<Link to={".."} state={router}>路由工厂列表</Link>}>
            <Form<GatewayRouteFactory>
                name="dynamic_form_nest_item"
                onFinish={onFinish}
                labelCol={{span: 4}}
                wrapperCol={{span: 16}}
                autoComplete="off"
                initialValues={{...factory, args, metadata}}
            >
                <Form.Item<GatewayRouteFactory> name={"id"} label={"数据编号"} hidden>
                    <Input/>
                </Form.Item>
                <Form.Item<GatewayRouteFactory> name={"name"} label={"工厂名字"}>
                    <Input/>
                </Form.Item>
                <Form.Item<GatewayRouteFactory> name={"type"} label={"工厂类型"}>
                    <Radio.Group>
                        <Radio value="predicate"> 断言工厂 </Radio>
                        <Radio value="filter"> 过滤器工厂 </Radio>
                    </Radio.Group>
                </Form.Item>
                <InputMultiple<GatewayRouteFactory> name={"args"} label={"工厂参数"}/>
                <InputMultiple<GatewayRouteFactory> name={"metadata"} label={"工厂元数据"}/>
                <Form.Item<GatewayRouteFactory> name={"remark"} label={"备注信息"}>
                    <TextArea rows={3}/>
                </Form.Item>
                <Form.Item wrapperCol={{span: 6, offset: 4}}>
                    <Button type="primary" htmlType="submit">
                        提交修改
                    </Button>
                </Form.Item>
            </Form>
        </Card>
    );
};

export default RouterFactoryUpdate;